//
//  LeftViewController.m
//  LeftRightSlider
//
//  Created by Zhao Yiqi on 13-11-27.
//  Copyright (c) 2013年 Zhao Yiqi. All rights reserved.
//

#import "LeftViewController.h"
#import "SliderViewController.h"
#import "CreateGroupVC.h"

#import "ChineseInclude.h"
#import "PinYinForObjc.h"

@interface LeftViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchDisplayDelegate>
{
    UITableView *_tableView;
    NSArray *_titleArray;

    //搜索框
    UISearchBar *mySearchBar;
    UISearchDisplayController *mySearchDisplayController;
    NSMutableArray *searchResults;
    
    NSMutableArray *dataArray;
    
}

@property (nonatomic, strong) UIButton *channelBtn;
@property (nonatomic, strong) CreateGroupVC *createGroupVC;
@end

@implementation LeftViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIImageView *imgV=[[UIImageView alloc] initWithFrame:self.view.bounds];
    imgV.backgroundColor = [UIColor darkGrayColor];
    [self.view addSubview:imgV];
    
    //初始化数据
    self.channelsGroup = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4", nil];
    self.privateGroup = [[NSMutableArray alloc]initWithObjects:@"slackbot", nil];
    self.directMsg = [[NSMutableArray alloc]initWithObjects:@"6",@"7", nil];
    _titleArray = [NSArray arrayWithObjects:@"CHANNELS", @"DIRECT MESSAGES", @"PRIVATE GROUPS",nil];
    
    [dataArray addObject:self.channelsGroup];
    [dataArray addObject:self.privateGroup];
    NSLog(@"1=====%@", dataArray);
    
//    [self initTableView];
//    [self initMysearchBarAndMysearchDisPlay];
    
    //搜索框
    mySearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
//    searchBar.frame = CGRectMake(0, 10, self.view.frame.size.width, self.view.frame.size.height);
    mySearchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    mySearchBar.delegate = self;
    mySearchBar.placeholder = @"Jump to...";
    mySearchBar.backgroundImage = [self imageWithColor:[UIColor clearColor] size:mySearchBar.bounds.size];

    mySearchDisplayController = [[UISearchDisplayController alloc]initWithSearchBar:mySearchBar contentsController:self];
    mySearchDisplayController.active = NO;
    mySearchDisplayController.searchResultsDataSource = self;
    mySearchDisplayController.searchResultsDelegate = self;

    //tableView
    _tableView = [[UITableView alloc] init];
    _tableView.frame = CGRectMake(0, 20, 210, self.view.frame.size.height);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor darkGrayColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.tableFooterView = [[UIView alloc] init];
    //    _tableView.tableHeaderView = [[UIView alloc] init];
    _tableView.tableHeaderView = mySearchBar;
    [self.view addSubview:_tableView];

//    UITableView *tableV=[[UITableView alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.height-100)];
//    tableV.backgroundColor=[UIColor clearColor];
//    tableV.delegate=self;
//    tableV.dataSource=self;
//    [self.view addSubview:tableV];
    
	// Do any additional setup after loading the view.
}

- (void)initTableView
{
    _tableView = [[UITableView alloc] init];
    _tableView.frame = CGRectMake(0, 20, 210, self.view.frame.size.height);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor darkGrayColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.tableFooterView = [[UIView alloc] init];
    //    _tableView.tableHeaderView = [[UIView alloc] init];
    _tableView.tableHeaderView = mySearchBar;
    [self.view addSubview:_tableView];
}

-(void)initMysearchBarAndMysearchDisPlay
{
    mySearchBar = [[UISearchBar alloc] init];
    mySearchBar.delegate = self;
    mySearchBar.placeholder = @"Jump to...";
    [mySearchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];//关闭键盘第一个字符大写功能
    [mySearchBar sizeToFit];
//    mySearchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    mySearchBar.backgroundImage = [self imageWithColor:[UIColor clearColor] size:mySearchBar.bounds.size];

//    加入列表的header里面
    _tableView.tableHeaderView = mySearchBar;
    
    mySearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:mySearchBar contentsController:self];
    mySearchDisplayController.delegate = self;
    mySearchDisplayController.searchResultsDataSource = self;
    mySearchDisplayController.searchResultsDelegate = self;
}

//取消searchbar背景色
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

#pragma mark 搜索框的代理方法，搜索输入框获得焦点（聚焦）
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    NSLog(@"ppppppppppp---searchBarTextDidBeginEditing-------");
//    [searchBar setShowsCancelButton:YES animated:YES];
//
//    // 修改UISearchBar右侧的取消按钮文字颜色及背景图片
//    for (UIView *searchbuttons in [searchBar subviews]){
//        if ([searchbuttons isKindOfClass:[UIButton class]]) {
//            UIButton *cancelButton = (UIButton*)searchbuttons;
//            // 修改文字颜色
//            [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//            [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
//
//            // 修改按钮背景
////            [cancelButton setBackgroundImage:[UIImage imageNamed:@"a"] forState:UIControlStateNormal];
//            [cancelButton setBackgroundColor:[UIColor redColor]];
//            [cancelButton setBackgroundImage:nil forState:UIControlStateHighlighted];
//        }
//    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//返回tableview有多少个section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_titleArray count];
}

//返回对应的section有多少个元素，也就是多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    if(tableView == mySearchDisplayController.searchResultsTableView)
//    {
//        tableView.frame = CGRectMake(0, 20, 320, self.view.frame.size.height-20);
//        //解决上面空出的20个像素
//        self.edgesForExtendedLayout = UIRectEdgeNone;
//        
////        return _resultsData.count;
//    }
//    else
//    {
////        return _dataArray.count;
//    }

//    NSMutableArray *itemArray = [self.dataList objectAtIndex:section];
//    NSLog(@"-----:%ld,%ld", section, itemArray.count);
//    return itemArray.count;
    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return searchResults.count;
    }
    else {
        NSInteger numRow = 0;
        
        if ( section == 0 ) {
            numRow = [self.channelsGroup count];
        }
        else if ( section == 1 )
        {
            numRow = [self.privateGroup count];
        }
        else if ( section == 2 )
        {
            numRow = [self.directMsg count];
        }
        
        return numRow;
    }
}

//这个方法返回指定的section的header view的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return tableView.rowHeight;
}

//返回指定的section的footer view的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return tableView.rowHeight;
}


//返回指定的row的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return tableView.rowHeight;
    return 20;
}

//返回指定的section的header的title，如果这个section header有返回view，那么title就不起作用了
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return _titleArray[section];
}


//返回指定的section header的view，如果没有，这个函数可以不返回view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(10.0, 0.0, 300.0, 44.0)];
    
    UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
//    headerLabel.backgroundColor = [UIColor clearColor];
//    headerLabel.opaque = NO;
    headerLabel.highlightedTextColor = [UIColor whiteColor];
    headerLabel.font = [UIFont systemFontOfSize:12];
    headerLabel.textColor = [UIColor whiteColor];
    headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 25);
    
    _channelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _channelBtn.frame = CGRectMake(190, 8, 15, 15);
    [_channelBtn setBackgroundImage:[UIImage imageNamed:@"addgroup.png"] forState:UIControlStateNormal];
    
    if (section == 0)
    {
        headerLabel.text = [_titleArray objectAtIndex:section];

        [_channelBtn addTarget:self action:@selector(channelBtn:) forControlEvents:UIControlEventTouchUpInside];
        [customView addSubview:self.channelBtn];
    }
    else if (section == 1)
    {
        headerLabel.text = [_titleArray objectAtIndex:section];
    }
    else if (section == 2)
    {
        headerLabel.text = [_titleArray objectAtIndex:section];

        [_channelBtn addTarget:self action:@selector(privateGroupBtn:) forControlEvents:UIControlEventTouchUpInside];
        [customView addSubview:self.channelBtn];
    }

    [customView addSubview:headerLabel];
    
    return customView;
}

- (void)channelBtn:(UIButton *)btn
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Create a New Channel" message:@"Enter a name for this channel" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    alert.backgroundColor = [UIColor blueColor];
    [alert show];
}

- (void)privateGroupBtn:(UIButton *)btn
{
    NSLog(@"===privateGroupBtn===");
    CreateGroupVC *createGroupVC = [[CreateGroupVC alloc] init];

    [self.navigationController pushViewController:createGroupVC animated:YES];
//    [self presentViewController:chatMainVC animated:YES completion:^{
//        
//    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)//cancel按钮
    {
        return;
        
    }
    else if(buttonIndex == 1)//ok按钮
    {

    }
}

//响应点击索引时的委托方法
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSLog(@"---sectionForSectionIndexTitle---");
    return index;
}

//返回指定的row 的cell。这个地方是比较关键的地方，一般在这个地方来定制各种个性化的cell元素。这里只是使用最简单最基本的cell 类型。其中有一个主标题cell.textLabel还有一个副标题cell.detailTextLabel, 还有一个image在最前头叫cell.imageView. 还可以设置右边的图标，通过cell.accessoryType可以设置是饱满的向右的蓝色箭头，还是单薄的向右箭头，还是勾勾标记。
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cellID";

    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    if( !cell)
    {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }

    cell.backgroundColor=[UIColor clearColor];
    tableView.allowsSelection=YES;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    UIView *view = cell.contentView;
  
    //标题
    {
        UILabel *label = [[UILabel alloc] init];
        if(indexPath.section == 0){
            label.text = [self.channelsGroup objectAtIndex:indexPath.row];
        }
        else if (indexPath.section == 1){
            label.text = [self.privateGroup objectAtIndex:indexPath.row];
        }
        else if (indexPath.section == 2){
            label.text = [self.directMsg objectAtIndex:indexPath.row];
        }

        label.frame = CGRectMake(10, 0, 140, 20);
        label.font = [UIFont systemFontOfSize:16.0];
        label.textColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1.0];
        [view addSubview:label];
    }
    
    return cell;
}

//当用户选中某个行的cell的时候，回调用这个。但是首先，必须设置tableview的一个属性为可以select才行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    switch (indexPath.row) {
//        case 0:
//            [[SliderViewController sharedSliderController] showContentControllerWithModel:@"MainViewController"];
//            break;
//        case 1:
//            [[SliderViewController sharedSliderController] showContentControllerWithModel:@"NaviViewController"];
//            break;
//        case 2:
//            [[SliderViewController sharedSliderController] showContentControllerWithModel:@"RightViewController"];
//            break;
//        default:
//            break;
//    }
    
//    //取消选中
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    
//    if (tableView == mySearchDisplayController.searchResultsTableView)
//    {
//        [self myAlertViewAccording:_resultsData[indexPath.row]];
//    }
//    else
//    {
//        [self myAlertViewAccording:_dataArray[indexPath.row]];
//    }
    
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
//        pv.nStr = searchResults[indexPath.row];
    }
    else
    {
        switch (indexPath.section) {
            case 0:

                break;
            case 1:
                
                break;
            default:
                break;
        }
    }
}

#pragma mark =====UISearchDisplayDelegate=====

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    searchResults = [[NSMutableArray alloc]init];
    if (searchBar.text.length>0&&![ChineseInclude isIncludeChineseInString:mySearchBar.text]) {
        for (int i=0; i<dataArray.count; i++) {
            if ([ChineseInclude isIncludeChineseInString:dataArray[i]]) {
                NSString *tempPinYinStr = [PinYinForObjc chineseConvertToPinYin:dataArray[i]];
                NSRange titleResult=[tempPinYinStr rangeOfString:mySearchBar.text options:NSCaseInsensitiveSearch];
                if (titleResult.length>0) {
                    [searchResults addObject:dataArray[i]];
                }
                NSString *tempPinYinHeadStr = [PinYinForObjc chineseConvertToPinYinHead:dataArray[i]];
                NSRange titleHeadResult=[tempPinYinHeadStr rangeOfString:mySearchBar.text options:NSCaseInsensitiveSearch];
                if (titleHeadResult.length>0) {
                    [searchResults addObject:dataArray[i]];
                }
            }
            else {
                NSRange titleResult=[dataArray[i] rangeOfString:mySearchBar.text options:NSCaseInsensitiveSearch];
                if (titleResult.length>0) {
                    [searchResults addObject:dataArray[i]];
                }
            }
        }
    } else if (mySearchBar.text.length>0&&[ChineseInclude isIncludeChineseInString:mySearchBar.text]) {
        for (NSString *tempStr in dataArray) {
            NSRange titleResult=[tempStr rangeOfString:mySearchBar.text options:NSCaseInsensitiveSearch];
            if (titleResult.length>0) {
                [searchResults addObject:tempStr];
            }
        }
    }
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    cell.frame = CGRectMake(-320, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
    [UIView animateWithDuration:0.7 animations:^{
        cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
    } completion:^(BOOL finished) {
        ;
    }];
}

@end
